package com.iot.lemon.task;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.iot.lemon.model.THouse;
import com.iot.lemon.model.TOrder;
import com.iot.lemon.service.THouseService;
import com.iot.lemon.service.TOrderService;
import com.iot.lemon.service.TOrderService.BizType;

import top.ibase4j.core.support.Pagination;
import top.ibase4j.core.util.DateUtil;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.ThreadUtil;

/**
 * @author ShenHuaJie
 * @since 2018年10月16日 下午3:47:11
 */
@Service(interfaceClass = OrderTask.class)
public class OrderTaskImpl implements OrderTask {
    private Logger logger = LogManager.getLogger();;
    @Autowired
    private THouseService houseService;
    @Autowired
    private TOrderService orderService;

    /** 生成物业费账单 */
    @Override
    public void createManageFeeTask() {
        THouse entity = new THouse();
        Integer total = houseService.count(entity);
        int pageSize = 100;
        Map<String, Object> params = InstanceUtil.newHashMap();
        params.put("pageSize", pageSize);
        ExecutorService executorService = ThreadUtil.threadPool(2, 10, 10);
        String month = DateUtil.getDateTime("yyyyMM");
        for (int i = 0; i < (total - 1) / pageSize + 1; i++) {
            params.put("pageIndex", i);
            Pagination<THouse> page = houseService.query(params);
            for (THouse house : page.getRecords()) {
                if (house.getManageFee() != null) {
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            TOrder entity = new TOrder().setHouseId(house.getId()).setOrderDate(month);
                            if (orderService.count(entity) == 0) {
                                entity.setOrgaId(house.getOrgaId());
                                entity.setVillageId(house.getVillageId());
                                entity.setOrderMoney(house.getManageFee());
                                entity.setBizType(BizType.SERVICE_FEE);
                                entity.setOrderTime(new Date());
                                entity.setCreateBy(0L);
                                orderService.update(entity);
                            }
                        }
                    });
                }
            }
        }
        executorService.shutdown();
        try {
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            logger.error("", e);
        }
    }
}
